package com.huisang.servlet.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.huisang.pojo.Role;
import com.huisang.pojo.User;
import com.huisang.service.role.RoleService;
import com.huisang.service.role.RoleServiceImpl;
import com.huisang.service.user.UserService;
import com.huisang.service.user.UserServiceImpl;
import com.huisang.util.Constants;
import com.huisang.util.PageSupport;
import com.mysql.jdbc.StringUtils;

//实现Servlet复用
public class UserServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       String method=req.getParameter("method");
       if(method.equals("savepwd")&&method!=null){
           this.updatePwd(req, resp);
       }else if(method.equals("pwdmodify")&&method!=null){
            this.pwdmodify(req, resp);
       }else if(method.equals("query")&&method!=null){
            this.query(req,resp);
       }else if(method.equals("getrolelist")&&method!=null){
           this.getRolelist(req, resp);
       }else if(method.equals("ucexist")&&method!=null){
           this.ucExist(req, resp);
       }else if(method.equals("add")&&method!=null){
           this.add(req, resp);
       }else if (method.equals("view")&&method!=null) {
        this.getUserById(req, resp, "userview.jsp");
       }else if (method.equals("modify")&&method!=null) {
        this.getUserById(req, resp, "usermodify.jsp");
       }else if (method != null && method.equals("modifyexe")) {
        this.modify(req, resp);
       }else if (method != null && method.equals("deluser")) {
        this.delUser(req, resp);
       }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    
    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        //从Session里面拿ID;
        Object attribute=req.getSession().getAttribute(Constants.USER_SESSION);

        String newpassword=req.getParameter("newpassword");

        boolean flag=false;
        //isNullOrEmpty判断一个字段内容是否为空
        //是空返回true，不是空则返回false
        if(attribute!=null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService=new UserServiceImpl();
            flag=userService.updatePwd(((User)attribute).getId(),newpassword);
            if(flag){
                req.setAttribute("message", "修改密码成功，请退出使用新密码登录！");
                //密码修改成功移除Session，要求重新登录
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute("message", "密码修改失败");
                //密码修改失败
            }
        }else{
            req.setAttribute("message", "新密码有问题");
        }

        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //验证旧密码,Session中有用户的密码
    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
        //从Session里面拿ID;
        Object attribute=req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword=req.getParameter("oldpassword");

        //万能Map
        HashMap<Object,Object> resultMap= new HashMap<Object,Object>();

        if(attribute==null){//Session失效或过期了
            resultMap.put("result", "sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//输入的密码为空
            resultMap.put("result", "error");
        }else{
            String userPassword=((User)attribute).getUserPassword();
            if(oldpassword.equals(userPassword)){
                resultMap.put("result", "true");
            }else{
                resultMap.put("result", "false");
            }
        }
    
        try {
            resp.setContentType("application/json");
            PrintWriter writer=resp.getWriter();
            //JSONArray 阿里巴巴的工具类,转换格式的
            /*
            resultMap=["result", "sessionerror","result", "error"]
            转换成Json的格式 {key:value}
            */
            //将结果集转换成json字符串
            writer.write(JSONArray.toJSONString(resultMap));
            //刷新
            writer.flush();
            //关闭
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //(重点)
    //显示用户页面
    public void query(HttpServletRequest req, HttpServletResponse resp){

        //查询用户列表
        //从前端获取数据
        String queryUserName=req.getParameter("queryname");
        String queryUserRole=req.getParameter("queryUserRole");//前端获得
        String pageIndex=req.getParameter("pageIndex");

        int userRole=0;//前端不选择queryUserRole可能为空，防止报错，先显示赋值为0
        //第一次进入请求，一定是第一页且页面大小固定
        int pageSize=5; //写到配置文件中，方便修改
        int currentPageNo=1;    //当前页数

        //准备调用用户事务
        UserService userService=new UserServiceImpl();
        //准备调用角色事务
        RoleService roleService=new RoleServiceImpl();
        
        if(queryUserName==null){
            queryUserName="";
        }
        if(queryUserRole!=null && !queryUserRole.equals("")){
            userRole=Integer.parseInt(queryUserRole);       //给查询赋值
        }
        if(pageIndex!=null){
            currentPageNo=Integer.parseInt(pageIndex);
        }
        //获取用户总数(分页:上一页，下一页的情况)
        int totalCount=userService.getUserCount(queryUserName, userRole);
        //总页数支持
        PageSupport pageSupport=new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        pageSupport.setTotalPageCountByRs();
        //从分页里面得到最大页数
        int totalPageCount=pageSupport.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo<1){//如果页面小于1，直接显示第一页
            currentPageNo=1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;//让其等于最后一页
        }

        //获取用户列表
        List<User> userList=userService.getUserList(queryUserName, userRole, currentPageNo, pageSize);
        req.setAttribute("userList", userList);

        //获取角色列表
        List<Role> roleList=roleService.getRoleList();
        req.setAttribute("roleList", roleList);

        //用户总数
        req.setAttribute("totalCount", totalCount);
        //当前页数
        req.setAttribute("currentPageNo", currentPageNo);
        //传递最大页数
        req.setAttribute("totalPageCount", totalPageCount);
        //查询用户名
        req.setAttribute("queryUserName", queryUserName);
        //查询角色
        req.setAttribute("queryUserRole", userRole);

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //添加用户页面获取用户角色列表
    public void getRolelist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
    //根据用户名查找用户列表
    public void ucExist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String queryUserCode=null;
        boolean flag=false;
        HashMap<Object,Object> userCodeMap= new HashMap<Object,Object>();
        queryUserCode=req.getParameter("userCode");
        UserService userService = new UserServiceImpl();
        flag=userService.boUser(queryUserCode);
        if(StringUtils.isNullOrEmpty(queryUserCode)){
            userCodeMap.put("userCode", "error");
        }else if(flag){
            userCodeMap.put("userCode", "exist");
        }else{
            userCodeMap.put("userCode", "true");
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer=resp.getWriter();
            //JSONArray 阿里巴巴的工具类,转换格式的
            /*
            resultMap=["result", "sessionerror","result", "error"]
            转换成Json的格式 {key:value}
            */
            //将结果集转换成json字符串
            writer.write(JSONArray.toJSONString(userCodeMap));
            //刷新
            writer.flush();
            //关闭
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //添加一个用户
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        UserService userService = new UserServiceImpl();
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        if (userService.add(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }
    }
    //通过id获得用户的所有信息
    public void getUserById(HttpServletRequest req, HttpServletResponse resp, String url)
            throws ServletException, IOException {
        String id = req.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(id)) {
            //调用后台方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserById(id);
            req.setAttribute("user", user);
            req.getRequestDispatcher(url).forward(req, resp);
        }

    }
    //修改用户信息
    public void modify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String id = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        if (userService.modify(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }
    }
    //删除用户
    public void delUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        Integer delId = 0;
        try {
            delId = Integer.parseInt(id);
        } catch (Exception e) {
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            UserService userService = new UserServiceImpl();
            if (userService.deleteUserById(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        //把resultMap转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
}
